<template>
  <div>
    <div>
      <el-input style="width: 200px; margin: 0 5px" placeholder="用户ID" v-model="userId"></el-input>
      <el-button type="primary" @click="userOrderList(1)">查询</el-button>
      <el-button type="danger" @click="resetting">重置</el-button>
    </div>
    <div style="margin: 10px 0">
      <el-button type="primary" plain @click="handleAdd">新增</el-button>
      <el-button type="danger" plain @click="delBatch">批量删除</el-button>
    </div>
    <el-table :data="tableData" stripe :header-cell-style="{backgroundColor: 'aliceblue' , color: '#666'}"
              @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"></el-table-column>
      <el-table-column prop="id" label="序号" align="center"></el-table-column>
      <el-table-column prop="userId" label="用户ID" align="center"></el-table-column>
      <el-table-column prop="deviceId" label="充电宝ID" align="center"></el-table-column>
      <el-table-column prop="ustime" label="使用时长" align="center"></el-table-column>
      <el-table-column prop="discount" label="折扣" align="center"></el-table-column>
      <el-table-column prop="coupon" label="优惠券" align="center"></el-table-column>
      <el-table-column prop="meet" label="应付金额" align="center"></el-table-column>
      <el-table-column prop="payment" label="实付金额" align="center"></el-table-column>
      <el-table-column prop="orderStatus" label="订单状态" align="center"></el-table-column>
      <el-table-column :formatter="formatDate" prop="orderDate" label="订单日期"  align="center"></el-table-column>
      <el-table-column label="操作" align="center">
        <template v-slot="scope">
          <el-button type="primary" plain @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="danger" plain @click="del(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="block">
      <el-pagination
          @current-change="handleCurrentChange"
          :current-page="pageIndex"
          :page-size="pageSize"
          layout="total, prev, pager, next"
          :total="total">
      </el-pagination>
    </div>

    <el-dialog title="用户订单" :visible.sync="AddDialogFormVisible" width="60%"
               :close-on-click-modal="false">
      <el-form :model="form" :rules="rules" ref="ruleForm" label-width="80px" style="margin-right: 20px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户ID" prop="userId">
              <el-input v-model="form.userId" placeholder="用户ID"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="充电宝ID" prop="deviceId">
              <el-input v-model="form.deviceId" placeholder="充电宝ID"
                        show-word-limit></el-input>
            </el-form-item>
          </el-col>

        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="使用时长" prop="ustime">
              <el-input v-model="form.ustime" placeholder="使用时长" @change="bingo()"
                        show-word-limit></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="折扣" prop="discount">
              <el-input v-model="form.discount" placeholder="折扣" show-word-limit @change="bingo()"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="优惠券" prop="coupon">
              <el-input v-model="form.coupon" placeholder="优惠券" show-word-limit @change="bingo()"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="应付金额" prop="meet">
              <el-input v-model="form.meet" placeholder="应付金额" show-word-limit disabled></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="实付金额" prop="payment">
              <el-input v-model="form.payment" placeholder="实付金额" show-word-limit disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="订单状态" prop="orderStatus">
              <el-select v-model="form.orderStatus" placeholder="请选择">
                <el-option value="已完成">已完成</el-option>
                <el-option value="待付款">待付款</el-option>
              </el-select>
              <!--              <el-input v-model="form.orderStatus" placeholder="订单状态" show-word-limit></el-input>-->
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="订单日期" prop="orderDate">
<!--          <el-input v-model="form.returnDate" placeholder="归还日期"></el-input>-->
          <el-date-picker
              v-model="form.orderDate"
              type="datetime"
              style="width: 100%"
              format="yyyy-MM-dd HH:mm:ss"
              placeholder="选择日期时间"
              default-time="12:00:00">
          </el-date-picker>
        </el-form-item>
        <div style="text-align: center; margin-bottom: 20px">
          <el-button type="primary" @click="AddDialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="save">保存</el-button>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import request from "@/utils/request";

export default {
  name: "UserOrder",
  data() {
    return {
      tableData: [], // 所有的数据
      pageIndex: 1, // 当前的页码
      pageSize: 5, // 每页显示的个数
      total: 0, // 数据的总条数
      AddDialogFormVisible: false,
      user: JSON.parse(localStorage.getItem('power-user') || '{}'), // 存储缓存
      form: {}, // 存储表单缓存
      rules: {
        userId: [{required: true, message: '请输入用户ID', trigger: 'blur'},],
        // model: [{required: true, message: '请输入省份', trigger: 'blur'},],
        // userId: [{required: true, message: '请输入名称', trigger: 'blur'},],
      },
      ids: [],
      userId: '',
    }
  },
  created() {
    this.userOrderList()
  },
  methods: {
    //  时间格式化专用
    formatDate(row, column) {
      // 获取单元格数据
      let data = row[column.property];
      if(data == null) {
        return null;
      }
      let dt = new Date(data)
      return dt.getFullYear() + '-' + (dt.getMonth() + 1) + '-' + dt.getDate() + ' ' + dt.getHours() + ':' + dt.getMinutes() + ':' + dt.getSeconds()
    },
    // 批量删除
    delBatch() {
      if (!this.ids.length) {
        this.$message.warning("请选择要删除的数据")
        return
      }
      // 二次确认
      this.$confirm('您确认删除这些数据吗？', '确认删除', {type: 'warning'}).then(res => {
        this.$request.delete('/userOrder/delete/batch', {data: this.ids}).then(res => {
          if (res.code === '200') {
            this.$message.success("操作成功")
            this.userOrderList(1)
          } else {
            this.$message.error(res.msg)
          }
        })
      }).catch(() => {
      })
    },
    handleSelectionChange(rows) { // 当前选中行的所有数据
      console.log(rows)
      this.ids = rows.map(v => v.id)
      // console.log(ids)
    },
    // 单个删除
    del(id) {
      // 二次确认
      this.$confirm('您确认删除吗？', '确认删除', {type: 'warning'}).then(res => {
        this.$request.delete('/userOrder/delete/' + id).then(res => {
          if (res.code === '200') {
            this.$message.success("操作成功")
            this.userOrderList(1)
          } else {
            this.$message.error(res.msg)
          }
        })
      }).catch(() => {
      })
    },


    handleEdit(row) { // 编辑数据
      // 给form对象赋值，注意要深拷贝数据
      this.form = JSON.parse(JSON.stringify(row))
      // 打开弹窗
      this.AddDialogFormVisible = true
    },
    handleAdd() { // 新增数据
      this.form = {}  // 新增数据的时候清空数据
      this.AddDialogFormVisible = true // 打开弹窗
    },
    save() { // 保存按钮触发的逻辑 它会触发新增或者修改
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          this.$request({
            // 因为修改是从行内元素拿到的，有id，因此可以作此判断
            // 判断有没id，如果有id说明是修改的方法，如果没有则是新增的方法
            method: this.form.id ? 'PUT' : 'POST',
            url: this.form.id ? '/userOrder/update' : '/userOrder/add',
            data: this.form
          }).then(res => {
            if (res.code === '200') {
              this.$message.success('保存成功')
              this.userOrderList(1)
              this.AddDialogFormVisible = false
            } else {
              this.$message.error(res.msg)
            }
          })
        }
      })
    },

    resetting() {
      this.userId = ''
      this.userOrderList()
    },
    userOrderList(pageIndex) { // 分页查询
      if (pageIndex) {
        this.pageIndex = pageIndex
      }
      request.get('/userOrder/selectByPage', {
        params: {
          pageIndex: this.pageIndex,
          pageSize: this.pageSize,
          userId: this.userId,
        }
      }).then(res => {
        if (res.code == '200') {
          this.tableData = res.data.records
          this.total = res.data.total
        }
      })
    },
    handleCurrentChange(pageIndex) {
      // 赋值
      this.pageIndex = pageIndex
      // 调用分页查询方法
      this.userOrderList()
    },
    //金额计算
    bingo() {
      let a = this.form.ustime;  // 使用时长
      let b = this.form.discount; //  折扣
      let c = this.form.coupon;   //  优惠券
      let d = 2;  // 每小时收费2元

      if (this.form.ustime == undefined || this.form.ustime <= 5){
        a = Number(0)
      }else if ( this.form.ustime >= 600){
        a = Number(10)
      }else {
        a = Math.ceil( Number(a / 60).toFixed(2))
      }
      if (this.form.discount == undefined){
        b = Number(0)
      }else if(this.form.discount >10 || this.form.discount< 0){
        this.$message.warning("请输入0-10之间的折扣")
      }else {
        b = Number(b * 0.1)
      }
      if (this.form.discount == undefined){
        c = Number(0)
      }
      //|| this.form.ustime <= 5)
      // 计算规则，ustime小于5分钟免费，超过5分钟每小时2元收费，封顶 十小时20元，每天的24:00重置时间
      //应付金额
      let gp = Number(d * a).toFixed(2);
      //实付金额
      let ap = Number((d * a) - (d * a * b) - c).toFixed(2);

      // console.log("这是使用时长"+a);
      // console.log("这是折扣"+b);
      // console.log("这是优惠券"+c);
      // console.log("应付金额"+gp);
      // console.log("实付金额"+ap);

      this.form.meet = Number(gp);
      this.form.payment = Number(ap);


    }
  },
}
</script>

<style scoped>

</style>